package com.socket.client.util;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import lombok.extern.slf4j.Slf4j;

/**
 * 来自webchat-secure#AESUtil
 */
@Slf4j
public class AESUtil {
    public static String encrypt(String plaintext, String key) {
        try {
            return getAES(key).encryptBase64(plaintext.getBytes());
        } catch (CryptoException e) {
            log.warn("加密消息出错:{}, 原因:{}", plaintext, e.getMessage());
        }
        return null;
    }

    public static String decrypt(String ciphertext, String key) {
        if (StrUtil.isNotEmpty(ciphertext)) {
            try {
                return getAES(key).decryptStr(ciphertext);
            } catch (CryptoException e) {
                log.warn("解密消息出错:{}, 原因:{}", ciphertext, e.getMessage());
            }
        }
        return StrUtil.EMPTY;
    }

    /**
     * Get the built-in AES object
     */
    public static AES getAES(String key) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < key.length() / 2; i++) {
            sb.append(Integer.toString(key.charAt(i), 16));
        }
        byte[] iv = HexUtil.decodeHex(sb.toString());
        return new AES(Mode.CBC, Padding.PKCS5Padding, StrUtil.bytes(key), iv);
    }
}
